package com.lld.im.tcp.utils;

import com.lld.im.codec.config.BootstrapConfig;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;

/**
 * @author: LunBoWang
 * @description: MqFactory 类用于创建和管理 RabbitMQ 连接和通道。
 * 它提供了一个静态方法 getConnection() 用于获取 RabbitMQ 连接，
 * 以及一个静态方法 getChannel() 用于获取指定名称的 RabbitMQ 通道。
 * 该类还提供了一个静态方法 init() 用于初始化 RabbitMQ 连接工厂。
 * @date: 2025/3/27 下午8:23
 * @version: 1.0
 */

public class MqFactory {

    private static ConnectionFactory factory=null;

    private static ConcurrentHashMap<String,Channel> channelMap=new ConcurrentHashMap<>();

    private static Connection getConnection() throws IOException, TimeoutException {
        Connection connection = factory.newConnection();
        return connection;
    }

    public static Channel getChannel(String channelName) throws IOException, TimeoutException {
        Channel channel = channelMap.get(channelName);
        if(channel==null){
            channel=getConnection().createChannel();
            channelMap.put(channelName, channel);
        }
        return channel;
    }

    public static void init(BootstrapConfig.Rabbitmq rabbitmq){
        if(factory==null){
            factory=new ConnectionFactory();
            factory.setHost(rabbitmq.getHost());
            factory.setPort(rabbitmq.getPort());
            factory.setUsername(rabbitmq.getUserName());
            factory.setPassword(rabbitmq.getPassword());
            factory.setVirtualHost(rabbitmq.getVirtualHost());
        }
    }
}
